import json
import sql
from flask import Blueprint, request
from requests import post

# 设备
equipment = Blueprint('EquipmentController', __name__)


# 获取设备信息
@equipment.route('/getEquipment')
def getEquipmentType():
    return '设备，拿到了'


# 添加设备信息
@equipment.route('/addEquipment', methods=['GET', 'POST'])
def addEquipment():
    # req = json.dumps(request.args)
    req = json.loads(request.data)
    name = req['name']
    type_id = req['type_id']
    addr = req['addr']
    res = sql.add_device(name, type_id, addr)
    if res > 0:
        return 'success'
    else:
        return 'Fail.This name already exists in database.'
    # return 'ok'


# 修改设备类别信息
@equipment.route('/updateEquipment', methods=['GET', 'POST'])
def updateEquipmentType():
    # req = json.dumps(request.args)
    # return req
    req = json.loads(request.data)
    d_id = req['id']
    name = req['name']
    type_id = req['type_id']
    addr = req['addr']
    res = sql.modify_device(d_id, name, type_id, addr)
    print('modify')
    if res > 0:
        return 'success'
    else:
        return 'Fail.This name already in database.'


# 删除设备信息
@equipment.route('/deleteEquipment', methods=['GET', 'POST'])
def deleteEquipmentType():
    req = json.loads(request.data)
    d_id = req['id']
    res = sql.delete_device(d_id)
    if res > 0:
        return 'success'
    else:
        return 'Fail.This name already in database.'


# 获取设备是否在线
@equipment.route('/statusEquipment', methods=['GET', 'POST'])
def statusEquipment():
    req = json.loads(request.data)
    addresseeId = req["addresseeId"]  # 收件人id
    device = sql.get_device(addresseeId)
    addr = str(device[3])
    addr = addr + '/downEquipmentFunction'
    req = json.dumps(req)
    try:
        req_info = post(url=addr, data=req)
        req_info = req_info.json()
    except Exception:
        req_info = {'data': {'status': '0'}}
    return req_info
